package com.hj.designmode;

import java.util.concurrent.Callable;

/**
 * @Author : hujing
 * @Date: 2025/6/20 14:38
 * @Description: 适配器模式,参考文献:https://liaoxuefeng.com/books/java/design-patterns/structural/adapter/index.html
 */
public class AdapterMode {

    public static void main(String[] args) {
        Task task = new Task(10L);
        //这里task没有实现Runnable接口,不能直接传递给Thread,需要一个适配器,把task转成实现了Runnable接口的对象
//        Thread thread = new Thread(task);
        // 通过转换器将task转成RunnableAdapter对象
        RunnableAdapter adapter = new RunnableAdapter(task);
        Thread thread = new Thread(adapter);
        thread.start();
    }
}

class RunnableAdapter implements Runnable{
    
    // 待转换的接口
    private Callable<Long> callable;
    
    public RunnableAdapter(Callable<Long> callable){
        this.callable = callable;
    }

    @Override
    public void run() {
        try {
            callable.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

class Task implements Callable<Long> {

    private long num;

    public Task(long num) {
        this.num = num;
    }

    @Override
    public Long call() throws Exception {
        long r = 0;
        for (int n = 1; n <= num; n++) {
            r += n;
        }
        System.out.println("result: " + r);
        return r;
    }
}
